package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author gxm
 * @since 2023-12-18
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {
    @Override
    public ResponseResult saveWmUser(WmUser wmUser) {
        //查询当前用户是否已经是自媒体人
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getApUserId, wmUser.getApUserId());
        WmUser one = this.getOne(wrapper);

        if (one == null) {
            //如果不是,就保存并返回
            wmUser.setCreatedTime(new Date());
            this.save(wmUser);
            return ResponseResult.okResult(wmUser);
        } else {
            //如果是,直接返回
            return ResponseResult.okResult(one);
        }
    }

    @Override
    public ResponseResult login(LoginDto dto) {
        //1. 根据用户名查询
        LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
        query.eq(WmUser::getName, dto.getName());
        WmUser adUser = this.getOne(query);
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2. 密码对比
        String salt = adUser.getSalt();
        String pwdStr = dto.getPassword() + salt;
        String md5Str = DigestUtils.md5DigestAsHex(pwdStr.getBytes());
        if (!md5Str.equals(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //3. 使用JWT生成token 使用用户id生成
        Map<String, Object> claimMap = new HashMap<>();
        claimMap.put("userId", adUser.getId());
        claimMap.put("name", adUser.getName());
        String token = AppJwtUtil.getToken(claimMap);

        //4. 定义返回的结果
        Map<String, Object> map = new HashMap<>();
        adUser.setPhone(null);
        adUser.setPassword(null);
        adUser.setSalt(null);
        map.put("user", adUser);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
